<?php

/**
 * 文档控制器
 * @author keluo<pycorvn@yeah.net>
 * @since 2015-11-30 17:26:10
 */
class DocController extends SCController {
        
    public function __construct() {
        parent::__construct();
    }
    
    public function __empty() {
        $api = SCS::request()->segment(1);
        strpos($api, '::') && $this->Api($api);
    }
    
    public function Index($api = '') {
        $docs = $this->GetDoc();
        
        $this->view->render(get_defined_vars());
    }
    
    public function Api($api) {
        $docs = $this->GetDoc();
        $doc = false;
        list($object, $method) = explode('::', $api);
        if(!isset($docs[$object])) throw new Exception('404');
        foreach($docs[$object] as $d) {
            if($d['api'] == $object.'/'.$method) {
                $doc = $d;
            }
        }
        if(!$doc) throw new Exception('404');
        #echo '<pre>';print_r($doc['return']);die;
        $example = Abyss::ExampleReturn($doc['return']);
        $example = json_encode(['status' => 1, 'data' => $example]);
        
        $this->view->render(get_defined_vars(), 'doc/api');
    }
    
    public function Run($api) {
        $query = [
            'api' => str_replace('::', '/', $api),
            'param' => SCS::request()->post()
        ];
        $data = Abyss::Instance()->Sink($query, true);
        echo $data;
    }
    
    protected function GetDoc() {
        $files = scandir(SC_CONTROLLER_PATH);
        sort($files);
        unset($files[0], $files[1]);
        foreach($files as $controller) {
            $controller = substr($controller, 0, strpos($controller, '.'));
            if(in_array($controller, ['IndexController', 'DocController'])) continue;
            $rc = new ReflectionClass($controller);
            $methods = $rc->getMethods(ReflectionMethod::IS_PUBLIC);
            $class = $rc->newInstance();
            foreach($methods as $i => $method) {
                if(preg_match('/^_+/', $method->name)) unset($methods[$i]);
                $action = $rc->getMethod($method->name);
                $action->invoke($class, null);
            }
        }
        return Abyss::Instance()->GetDoc();
    }
}